import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, Select, Calendar, Typography, Badge,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';
let UUID = require('uuid-js');
import find from 'lodash/find';
import findIndex from 'lodash/findIndex';
import styles from './index.less';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import {
  sortableContainer,
  sortableElement,
  sortableHandle,
} from 'react-sortable-hoc';
import arrayMove from 'array-move';

import BuildModalTitle from '@/components/BuildModalTitle';
import AddOrEditPrice from './AddOrEditPrice';
import menu from './../../images/menu.png';
import plus from './../../images/plus.png';

const FormItem = Form.Item;
const { confirm } = Modal;
const { TextArea } = Input;
const RadioButton = Radio.Button;
const { Text } = Typography;
const RadioGroup = Radio.Group;


@connect(({ custom_menu, loading, global }) => ({
  custom_menu,
  global,
  loading: loading.models.custom_menu,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: [],
      selectedRowKeys: [],
      btnLoading: false,
      nowDate: moment().format('YYYY-MM-DD'),
      items: [{
        key:'营业厅',
        name:'营业厅',
        subMenu:[{
          name:'户号绑定',
          type:'link',
          content:'http://www.baidu.com'
        },{
          name:'水费账单',
          type:'text',
          content:'http://www.baidu.com'
        },{
          name:'缴费记录',
          type:'link',
          content:'http://www.baidu.com'
        },{
          name:'自助缴费',
          type:'text',
          content:'http://www.baidu.com'
        },{
          name:'水量自拍',
          type:'link',
          content:'http://www.baidu.com'
        }]
      },{
        key:'公共信息',
        name:'公共信息',
        subMenu:[{
          name:'企业宣传',
          type:'link',
          content:'http://www.baidu.com'
        },{
          name:'网上服务',
          type:'text',
          content:'http://www.baidu.com'
        },{
          name:'停水公告',
          type:'link',
          content:'http://www.baidu.com'
        }]
      },{
        key:'微网厅',
        name:'微网厅',
        subMenu:[{
          name:'新网厅',
          type:'link',
          content:'http://www.baidu.com'
        }]
      }],
      bottomActive:'',
      subActive:'',

    };
  }


  componentDidMount() {
    this.setState({
      bottomActive:this.state.items[0].key
    })
    const { dispatch } = this.props;
    const {
      custom_menu: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      // setTimeout(() => {
      //   table.scrollTop = scrollData.y;
      //   table.scrollLeft = scrollData.x;
      // }, 0);

    } else {
      const {
        custom_menu: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'custom_menu/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'custom_menu/changeLoaded',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    // table.addEventListener('scroll', debounce(this.scroll, 150));
  }


  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'custom_menu/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };
  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
  };
  onSortEnd = ({oldIndex, newIndex}) => {
    console.log('oldIndex, newIndex',oldIndex, newIndex)
    const {
      dispatch,custom_menu: { button:items },
    } = this.props;
    dispatch({
      type: 'custom_menu/changeButton',
      payload: arrayMove(items, oldIndex, newIndex),
    });
    // this.setState(({items}) => ({
    //   items: arrayMove(items, oldIndex, newIndex),
    // }),function() {
    //   console.log('items',this.state.items)
    // });
  };
  addBottomItem=()=>{
    const {
      dispatch,custom_menu: { button:items,bottomActive,subActive },
    } = this.props;
    items.push({
      name:'菜单名称',
      uuid:UUID.create().toString(),
      sub_button:[]
    })
    dispatch({
      type: 'custom_menu/changeButton',
      payload: items,
    });
  }
  deleteMenu=(index)=>{
    const {
      dispatch,custom_menu: { button:items,bottomActive,subActive },
    } = this.props;
    if(items.length===0){
      message.error('微信公众号至少需要一个菜单');
      return false
    }
    items.splice(index,1);
    console.log('items',items)
    dispatch({
      type: 'custom_menu/changeBottomActive',
      payload: items[0].uuid,
    });
    dispatch({
      type: 'custom_menu/changeButton',
      payload: items,
    });
    // this.setState({
    //   bottomActive:items[0].key,
    //   items
    // })
  }
  deleteSubMenu=(index,subIndex)=>{
    const {
      dispatch,custom_menu: { button:items,bottomActive,subActive },
    } = this.props;
    items[index].sub_button.splice(subIndex,1);
    console.log('items',items)
    dispatch({
      type: 'custom_menu/changeBottomActive',
      payload: items[index].uuid,
    });
    dispatch({
      type: 'custom_menu/changeSubActive',
      payload: '',
    });
    dispatch({
      type: 'custom_menu/changeButton',
      payload: items,
    });
    // this.setState({
    //   bottomActive:this.state.items[index].key,
    //   subActive:'',
    //   items
    // })
  }

  addSubMenu=(index)=>{
    const {
      dispatch,custom_menu: { button:items,bottomActive,subActive },
    } = this.props;
    items[index].sub_button.push({
      name:`子菜单名称`,
      type:'view',
      url:'',
      uuid:UUID.create().toString()
    })
    console.log('items',items);
    dispatch({
      type: 'custom_menu/changeButton',
      payload: items,
    });
    // this.setState({
    //   items
    // },function() {
    //   console.log('addSubMenu this.state.item',this.state.items)
    // })
  }
  sortSubMenu=(sort,index,subIndex)=>{
    const {
      dispatch,custom_menu: { button:items,bottomActive,subActive },
    } = this.props;
    let fieldData=items[index].sub_button;
    fieldData[subIndex] = fieldData.splice(subIndex+sort, 1, fieldData[subIndex])[0];
    items[index].sub_button=fieldData;
    dispatch({
      type: 'custom_menu/changeButton',
      payload: items,
    });
  }
  changeValue=(value,index,subIndex)=>{
    const {
      dispatch,custom_menu: { button:items,bottomActive,subActive },
    } = this.props;
    if(subIndex===undefined){
      items[index].name=value
    }else{
      items[index].sub_button[subIndex].name=value
    }
    dispatch({
      type: 'custom_menu/changeButton',
      payload: items,
    });
  }
  changeURLValue=(value,index,subIndex)=>{
    const {
      dispatch,custom_menu: { button:items,bottomActive,subActive },
    } = this.props;
    items[index].sub_button[subIndex].url=value
    dispatch({
      type: 'custom_menu/changeButton',
      payload: items,
    });
  }
  saveMenu=()=>{
    const {
      dispatch,custom_menu: { button:items,bottomActive,subActive },
    } = this.props;
    dispatch({
      type: 'custom_menu/edit',
      payload: items,
      callback:()=>{
        message.success('保存发布新菜单成功')
      }
    });
  }
  render() {
    const that = this;
    const {
      dispatch,custom_menu: { button,bottomActive,subActive,clean },
    } = this.props;
    console.log('button',button)
    const currentItem = find(button,(o)=>{return o.uuid===bottomActive});
    const currentItemIndex = findIndex(button,(o)=>{return o.uuid===bottomActive});
    let currentSubItem=''
    let currentSubItemIndex=''
    if(currentItem&&subActive){
      currentSubItem = find(currentItem.sub_button,(o)=>{return o.uuid===subActive});
      currentSubItemIndex = findIndex(currentItem.sub_button,(o)=>{return o.uuid===subActive});
    }
    const DragHandle = sortableHandle(() => <img className={"bottom_img"} src={menu} alt=""/>);
    const SortableContainer = sortableContainer(({ children }) => {
      return <div className={"phone_bottom"}>{children}</div>;
    });
    console.log('currentSubItemIndex',currentSubItemIndex)
    const SortableItem = sortableElement(({ value }) =>
      <div className={"bottom_item"}>
        <DragHandle /><span className={bottomActive===value.uuid?'active':''} onClick={()=>{
        dispatch({
          type: 'custom_menu/changeBottomActive',
          payload: value.uuid,
        });
        dispatch({
          type: 'custom_menu/changeSubActive',
          payload:'',
        });
          // that.setState({
          //   bottomActive:value.uuid,
          //   subActive:''
          // })
      }}>{value.name}</span>
        {
          bottomActive===value.uuid&&
          <div className={"bottom_submenu"}>
            {
              value.sub_button.map((item,index)=>{
                return <div onClick={()=>{
                  dispatch({
                    type: 'custom_menu/changeSubActive',
                    payload:item.uuid,
                  });
                }} className={`submenu_item ${subActive===item.uuid?'active':''}`} key={index}>{item.name}</div>
              })
            }
            {
              value.sub_button.length!==5&& <div onClick={()=>{that.addSubMenu(currentItemIndex)}} className={"submenu_item"} style={{padding:'0 11px 5px',width:'76px'}}><img src={plus} alt=""/></div>

            }
          </div>
        }
      </div>
    );

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>公众号自定义菜单</span>
      </div>
      <div className="table-page" style={{ padding: '12px', display: 'flex' }}>
        <div className={"phone_box"}>
          <h2 className={"phone_title"} title={'吐鲁番市天源水务有限公司'}>吐鲁番市天源水务有限公司</h2>
          <SortableContainer axis="x"  onSortEnd={this.onSortEnd} useDragHandle>
            {
              button.map((item, index) => {
                return <SortableItem key={`item-${index}`} index={index} value={item} />

              })
            }
            {
              button.length<3&&
              <div className={"bottom_item"} onClick={that.addBottomItem} >
                <img className={'bottom_add'} src={plus} alt=""/>
              </div>
            }
          </SortableContainer>
          <div>
            {
              !clean&&
              <Button className={"phone_button"}  type={'primary'} size={'large'} block onClick={()=>{
                confirm({
                  title: `确定要保存并发布新菜单吗?`,
                  content: '请谨慎操作！',
                  okText: '确定',
                  okType: 'primary',
                  cancelText: '取消',
                  centered:true,
                  maskClosable: true,
                  onOk() {
                    that.saveMenu()
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                })
              }}>保存并发布</Button>
            }
          </div>
        </div>
        <div className={"content_box"} style={{background:clean?'#f4f5f9':'#fff2f5'}}>
          <h3 className={"content_title"}>
            {
              (bottomActive && !subActive) ? currentItem.name:currentSubItem.name
            }
            {
              subActive?
                <span style={{color:'#f00'}} onClick={()=>{
                  confirm({
                    title: `确定要删除子菜单吗?`,
                    content: '请谨慎操作！',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    centered:true,
                    maskClosable: true,
                    onOk() {
                      that.deleteSubMenu(currentItemIndex,currentSubItemIndex)
                    },
                    onCancel() {
                      console.log('Cancel');
                    },
                  })
                }} >删除子菜单</span>:
                <span style={{color:'#f00'}}  onClick={()=>{
                  confirm({
                    title: `确定要删除菜单吗?`,
                    content: '请谨慎操作！',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    centered:true,
                    maskClosable: true,
                    onOk() {
                      that.deleteMenu(currentItemIndex)
                    },
                    onCancel() {
                      console.log('Cancel');
                    },
                  })
                }}
                >删除菜单</span>
            }
            {
              subActive?
                <Fragment>
                  {
                    currentSubItemIndex!==currentItem.sub_button.length-1&&
                    <span onClick={()=>{
                      this.sortSubMenu(1,currentItemIndex,currentSubItemIndex)
                    }}>下移</span>
                  }
                  {
                    currentSubItemIndex!==0&&
                    <span onClick={()=>{
                      this.sortSubMenu(-1,currentItemIndex,currentSubItemIndex)
                    }}>上移</span>
                  }
                </Fragment>:
                ""
            }

          </h3>
          {
            (currentItem&&currentItem.sub_button.length>=5&&!subActive)&&
            <div className={"content_tip"}>
              已为“营业厅”添加了5个子菜单，无法设置其他内容。
            </div>
          }
          {
            (bottomActive&&!subActive)?
            <div style={{ marginTop: '10px' }}>
              <Form layout={'inline'}>
                <FormItem
                  label={(
                    <span>
               菜单名称
            </span>
                  )}
                  help="仅支持中英文和数字，字数不超过4个汉字或8个字母"
                >
                  <Input value={currentItem.name} onChange={(e)=>{
                    this.changeValue(e.target.value,currentItemIndex)
                  }}/>
                </FormItem>
              </Form>
            </div>:
              <div>
                <div style={{ marginTop: '10px' }}>
                  <Form layout={'inline'}>
                    <FormItem
                      label={(
                        <span>
                          子菜单名称
                        </span>
                      )}
                      help="仅支持中英文和数字，字数不超过4个汉字或8个字母"
                    >
                      <Input  value={currentSubItem.name} onChange={(e)=>{
                        this.changeValue(e.target.value,currentItemIndex,currentSubItemIndex)
                      }}/>
                    </FormItem>
                  </Form>
                </div>
                <div>
                  <Form layout={'inline'}>
                    <FormItem
                      label={(
                        <span>
               子菜单内容
            </span>
                      )}
                    >
                      <Radio.Group value={currentSubItem.type}>
                        <Radio value="view">跳转网页</Radio>
                      </Radio.Group>
                    </FormItem>
                  </Form>
                </div>
                {
                  currentSubItem.type==='view'&&
                  <div className={"content_value"}>
                    <div className={"content_tip"} style={{ marginTop: '0' }}>
                      订阅者点击该子菜单会跳到以下链接
                    </div>
                    <div style={{ marginTop: '10px' }}>
                      <Form layout={'inline'}>
                        <FormItem
                          label={(
                            <span>
               页面地址
            </span>
                          )}
                          help="请输入链接"
                        >
                          <Input style={{ width: '320px' }}  value={currentSubItem.url} onChange={(e)=>{
                            this.changeURLValue(e.target.value,currentItemIndex,currentSubItemIndex)
                          }}/>
                        </FormItem>
                      </Form>
                    </div>
                  </div>
                }
               {/* <div className={"content_value"}>
                  <div className={"content_tip"} style={{ marginTop: '0' }}>
                    订阅者点击该子菜单会回复以下文字
                  </div>
                  <div style={{ marginTop: '10px' }}>
                    <Form layout={'inline'}>
                      <FormItem
                        label={(
                          <span>
               回复文字
            </span>
                        )}
                      >
                        <TextArea rows={4} style={{ width: '320px', marginTop: '4px', resize: 'none' }}/>
                      </FormItem>
                    </Form>
                  </div>
                </div>*/}
              </div>
          }


        </div>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`${this.state.nowDate} 事务`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        okButtonProps={{ loading: this.state.btnLoading }}
        className="editModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}

      >
        <AddOrEditPrice
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />

      </Modal>
    </div>;
  }
}

export default BasicList;
